//
//  SignViewController.m
//  GuoBuGaForIphone
//
//  Created by zhangwo on 16/10/26.
//  Copyright © 2016年 GuoBuGa. All rights reserved.
//

#import "SignViewController.h"

@interface SignViewController ()
{
    NSDictionary *status;
}

@end

@implementation SignViewController
@synthesize mapView = _mapView;
@synthesize locationManager = _locationManager;
@synthesize geocoder = _geocoder;
@synthesize city = _city;
@synthesize address = _address;

@synthesize locaLabel = _locaLabel;
@synthesize timeLabel = _timeLabel;
@synthesize remarksView = _remarksView;

- (instancetype)init
{
    self = [super init];
    if (self) {
        if ([APIKey length] == 0) {
            NSString *reason = [NSString stringWithFormat:@"apiKey为空，请检查key是否正确设置。"];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:reason delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            
            [alert show];
        }
        [AMapServices sharedServices].apiKey = (NSString *)APIKey;
        
        //请求定位服务
        _locationManager=[[CLLocationManager alloc]init];
        if(![CLLocationManager locationServicesEnabled]||[CLLocationManager authorizationStatus]!=kCLAuthorizationStatusAuthorizedWhenInUse){
            [_locationManager requestWhenInUseAuthorization];
            // 开始定位
            // 取得定位权限，有两个方法，取决于你的定位使用情况
            // 一个是requestAlwaysAuthorization，一个是requestWhenInUseAuthorization
            [_locationManager requestAlwaysAuthorization];
            // 设置定位精确度到米
            _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
            // 设置过滤器为无
            _locationManager.distanceFilter = kCLDistanceFilterNone;
            //定位频率,每隔多少米定位一次
            CLLocationDistance distance=10.0;//十米定位一次
            _locationManager.distanceFilter=distance;
            //启动跟踪定位
            [_locationManager startUpdatingLocation];
        }
        
        //用户位置追踪(用户位置追踪用于标记用户当前位置，此时会调用定位服务)
        _mapView.userTrackingMode=MKUserTrackingModeFollow;
        //设置地图类型
        _mapView.mapType=MKMapTypeStandard;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    ///初始化地图
    _mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, SWIDTH, SHEIGHT/2+50)];
    _mapView.delegate = self;
    _mapView.showsUserLocation = YES;
    [_mapView setUserTrackingMode:MKUserTrackingModeFollow animated:YES];
    [self.view addSubview:_mapView];
    
    
    UIButton *recordBtn = [[UIButton alloc] initWithFrame:CGRectMake(SWIDTH-100, 60, 100, 30)];
    [recordBtn setTitle:@"打卡记录" forState:UIControlStateNormal];
    recordBtn.layer.cornerRadius = 10;
    [recordBtn setTitleColor:[UIColor colorWithHexString:@"0x0092F2"] forState:UIControlStateNormal];
    [recordBtn setBackgroundColor:[[UIColor grayColor] colorWithAlphaComponent:0.2]];
    [recordBtn addTarget:self action:@selector(recordButton:) forControlEvents:UIControlEventTouchUpInside];
    [_mapView addSubview:recordBtn];
    
    [self getCoordinateByAddress:@"六盘水"];
    [self getAddressByLatitude:39.54 longitude:116.28];//经纬度
    CLLocationCoordinate2D coordinate = [[DSXCLLocationManager sharedManager] coordinate];
    NSString *location = [NSString stringWithFormat:@"%f,%f",coordinate.longitude,coordinate.latitude];
    
//    UIView *sginView = [[UIView alloc] initWithFrame:CGRectMake(10, SHEIGHT/2+50, SWIDTH, SHEIGHT - _mapView.frame.size.height-60)];
    
    _locaImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, SHEIGHT/2+65, 25, 25)];
    _locaImage.image = [UIImage imageNamed:@"icon-sgin-loca.png"];
    [self.view addSubview:_locaImage];
    
    _locaLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, SHEIGHT/2+50, SWIDTH-65, 50)];
    _locaLabel.text = [NSString stringWithFormat:@"当前位置:%@",location];
    _locaLabel.numberOfLines = 2;
    _locaLabel.font = [UIFont systemFontOfSize:14.0];
    [self.view addSubview:_locaLabel];
    
    _timeImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, SHEIGHT/2+105, 25, 25)];
    _timeImage.image = [UIImage imageNamed:@"icon-sgin-time.png"];
    [self.view addSubview:_timeImage];
    
    _timeNow = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timerFunc) userInfo:nil repeats:YES];
    _timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, SHEIGHT/2+105, SWIDTH-65, 25)];
    _timeLabel.font = [UIFont systemFontOfSize:14.0];
    [self.view addSubview:_timeLabel];
    
    _remarkImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, SHEIGHT/2+135, 25, 25)];
    _remarkImage.image = [UIImage imageNamed:@"icon-remarks-image.png"];
    [self.view addSubview:_remarkImage];
    
    _remarksView = [[UITextView alloc] initWithFrame:CGRectMake(40, SHEIGHT/2+130, SWIDTH-65, 30)];
    _remarksView.textColor = [UIColor blackColor];
    _remarksView.delegate = self;
    _remarksView.scrollEnabled = NO;
    _remarksView.layer.masksToBounds = NO;
    _remarksView.font = [UIFont systemFontOfSize:16.0f];
    _remarksView.textContainerInset = UIEdgeInsetsMake(5, 0, 5, 5);
    _remarksView.textContainerInset = UIEdgeInsetsMake(5, 0, 5, 5);
    
    //提示语句
    _placeHolder = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    _placeHolder.text = @"备注";
    _placeHolder.textColor = [UIColor colorWithHexString:@"0x0092F2"];
    _placeHolder.font = [UIFont systemFontOfSize:16.0f];
//    [_placeHolder sizeToFit];
    [_remarksView addSubview:_placeHolder];
    [self.view addSubview:_remarksView];
    [_remarksView becomeFirstResponder];
    
    
    _sginButton = [[UIButton alloc] initWithFrame:CGRectMake(SWIDTH/2-40, SHEIGHT-130, SWIDTH/5, SWIDTH/5)];
    _sginButton.layer.cornerRadius = _sginButton.frame.size.width/2;
    [self.view addSubview:_sginButton];
    
    //签到
    NSDictionary *signIn = @{@"uid":@([BJUserStatus sharedStatus].uid),
                             @"status":@(0),
                             @"address":_locaLabel.text,
                             @"message":_remarksView.text
                             };
    
    //签退
//    NSDictionary *params = @{@"uid":@([BJUserStatus sharedStatus].uid),
//                             @"status":@(1),
//                             @"address":_locaLabel.text,
//                             @"message":_remarksView.text
//                             };
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];//设置相应内容类型
    [manager GET:@"http://gpj.zhangwoo.cn/app.php?platform=ios&appkey=5a379b5eed8aaae531df5f60b12100cfb6dff2c1&c=sign&a=validation"
      parameters:@{@"uid":@([BJUserStatus sharedStatus].uid)} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            int signStatus = [[responseObject objectForKey:@"data"] intValue];
//            NSLog(@"%d",signStatus);
            if (signStatus == 1) {
                [_sginButton setBackgroundImage:[UIImage imageNamed:@"icon-sgin-image.png"] forState:UIControlStateNormal];
                [_sginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                [_sginButton setTitle:@"签退" forState:UIControlStateNormal];
                [_sginButton addTarget:self action:@selector(sginOut:) forControlEvents:UIControlEventTouchUpInside];
//                NSLog(@"%d",signStatus);
            }
            else if (signStatus == 2) {
                [_sginButton setBackgroundImage:[UIImage imageNamed:@"icon-sginOut-image.png"] forState:UIControlStateNormal];
                [_sginButton setTitle:@"已签退" forState:UIControlStateNormal];
                [_sginButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
//                NSLog(@"%d",signStatus);
            }
            else
            {
                [[DSXHttpManager sharedManager] GET:@"&c=sign&a=createreach" parameters:signIn progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    if ([responseObject isKindOfClass:[NSDictionary class]]) {
                        [_sginButton setBackgroundImage:[UIImage imageNamed:@"icon-sgin-image.png"] forState:UIControlStateNormal];
                        [_sginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                        [_sginButton setTitle:@"签到" forState:UIControlStateNormal];
                        [_sginButton addTarget:self action:@selector(sginChange:) forControlEvents:UIControlEventTouchUpInside];
//                        NSLog(@"%d",signStatus);
                    }
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    
                }];
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];

    //添加大头针
    [self addAnnotation];
}

//打卡记录
- (void)recordButton:(UIButton *)button
{
    RecordViewController *recordView = [[RecordViewController alloc] init];
    DSXNavigationController *nav = [[DSXNavigationController alloc] initWithRootViewController:recordView];
    [self.navigationController presentViewController:nav animated:YES completion:nil];
}

//上传图片 备注
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    RemarksViewController *remarksView = [[RemarksViewController alloc] init];
    [self.navigationController pushViewController:remarksView animated:YES];
    return NO;
}

//textView 提示语句显示与隐藏
- (void)textViewDidChange:(UITextView *)textView{
    if (self.remarksView.text.length > 0) {
        _placeHolder.hidden = YES;
    }else {
        _placeHolder.hidden = NO;
    }
}

//显示当前时间
- (void)timerFunc
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"当前时间:HH:mm"];
    _timestamp = [formatter stringFromDate:[NSDate date]];
    [_timeLabel setText:_timestamp];
}


//签退
- (void)sginChange:(UIButton *)button
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"签到成功!" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
    [alert show];
    [NSTimer scheduledTimerWithTimeInterval:1.5f target:self selector:@selector(timerFireMethod:) userInfo:alert repeats:YES];
    [alert show];
    
    [button removeTarget:self action:@selector(sginChange:) forControlEvents:UIControlEventTouchUpInside];//移除点击事件
    _sginButton = button;
    _sginButton.selected = button.selected;
    NSDictionary *params = @{@"uid":@([BJUserStatus sharedStatus].uid),
                             @"status":@"1",
                             @"address":_locaLabel.text,
                             @"message":_remarksView.text
                             };
    
    [[DSXHttpManager sharedManager] POST:@"&c=sign&a=createback" parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            [button setTitle:@"签退" forState:UIControlStateNormal];
            [button addTarget:self action:@selector(sginOut:) forControlEvents:UIControlEventTouchUpInside];
//            NSLog(@"%@",status);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
    
}

-(void)timerFireMethod:(NSTimer*)theTimer//弹出框
{
    UIAlertView *promptAlert = (UIAlertView*)[theTimer userInfo];
    [promptAlert dismissWithClickedButtonIndex:0 animated:NO];
    promptAlert =NULL;
}

//签退成功
- (void)sginOut:(UIButton *)button
{
    [status isEqual:@"2"];
    _sginButton = button;
    _sginButton.selected = button.selected;
    [button setBackgroundImage:[UIImage imageNamed:@"icon-sginOut-image.png"] forState:UIControlStateNormal];
    [button setTitle:@"已签退" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
}


//添加大头针
- (void)addAnnotation
{
    CLLocationCoordinate2D location1=CLLocationCoordinate2DMake(39.95, 116.35);
    MyAnnotation *annotation1=[[MyAnnotation alloc]init];
    annotation1.title=@"CMJ Studio";
    annotation1.subtitle=@"Kenshin Cui's Studios";
    annotation1.coordinate=location1;
    [_mapView addAnnotation:annotation1];
    
    CLLocationCoordinate2D location2=CLLocationCoordinate2DMake(39.87, 116.35);
    MyAnnotation *annotation2=[[MyAnnotation alloc]init];
    annotation2.title=@"Kenshin&Kaoru";
    annotation2.subtitle=@"Kenshin Cui's Home";
    annotation2.coordinate=location2;
    [_mapView addAnnotation:annotation2];
    
}

#pragma mark - 地图控件代理方法
#pragma mark 更新用户位置，只要用户改变则调用此方法（包括第一次定位到用户位置）
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
    
    NSLog(@"%@",userLocation);
    //设置地图显示范围(如果不进行区域设置会自动显示区域范围并指定当前用户位置为地图中心点)
    MKCoordinateSpan span=MKCoordinateSpanMake(0.01, 0.01);
    MKCoordinateRegion region=MKCoordinateRegionMake(userLocation.location.coordinate, span);
    [_mapView setRegion:region animated:true];
}

#pragma mark - CoreLocation 代理
#pragma mark 跟踪定位代理方法，每次位置发生变化即会执行（只要定位到相应位置）
//可以通过模拟器设置一个虚拟位置，否则在模拟器中无法调用此方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    //此处locations存储了持续更新的位置坐标值，取最后一个值为最新位置，如果不想让其持续更新位置，则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
    CLLocation *location=[locations lastObject];//取出第一个位置
    CLLocationCoordinate2D coordinate=location.coordinate;//位置坐标

//    CLLocationDegrees latitude = location.coordinate.latitude;
//    CLLocationDegrees longitude = location.coordinate.longitude;
    NSLog(@"经度：%f,纬度：%f,海拔：%f,航向：%f,行走速度：%f",coordinate.longitude,coordinate.latitude,location.altitude,location.course,location.speed);
    //如果不需要实时定位，使用完即使关闭定位服务
    [_locationManager stopUpdatingLocation];
}

#pragma mark 根据地名确定地理坐标
-(void)getCoordinateByAddress:(NSString *)address{
    //地理编码
    [_geocoder geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error) {
        //取得第一个地标，地标中存储了详细的地址信息，注意：一个地名可能搜索出多个地址
        CLPlacemark *placemark=[placemarks firstObject];
        
        CLLocation *location=placemark.location;//位置
        CLRegion *region=placemark.region;//区域
        NSDictionary *addressDic= placemark.addressDictionary;//详细地址信息字典,包含以下部分信息
        //        NSString *name=placemark.name;//地名
        //        NSString *thoroughfare=placemark.thoroughfare;//街道
        //        NSString *subThoroughfare=placemark.subThoroughfare; //街道相关信息，例如门牌等
        //        NSString *locality=placemark.locality; // 城市
        //        NSString *subLocality=placemark.subLocality; // 城市相关信息，例如标志性建筑
        //        NSString *administrativeArea=placemark.administrativeArea; // 州
        //        NSString *subAdministrativeArea=placemark.subAdministrativeArea; //其他行政区域信息
        //        NSString *postalCode=placemark.postalCode; //邮编
        //        NSString *ISOcountryCode=placemark.ISOcountryCode; //国家编码
        //        NSString *country=placemark.country; //国家
        //        NSString *inlandWater=placemark.inlandWater; //水源、湖泊
        //        NSString *ocean=placemark.ocean; // 海洋
        //        NSArray *areasOfInterest=placemark.areasOfInterest; //关联的或利益相关的地标
        NSLog(@"位置:%@,区域:%@,详细信息:%@",location,region,addressDic);
    }];
}

#pragma mark 根据坐标取得地名
-(void)getAddressByLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude{
    //反地理编码
    CLLocation *location=[[CLLocation alloc]initWithLatitude:latitude longitude:longitude];
    [_geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *placemark=[placemarks firstObject];
        NSLog(@"详细信息:%@",placemark.addressDictionary);
    }];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    [self.locationManager startUpdatingLocation];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
